#!/usr/bin/env ruby

require 'rubygems'
require 'snmp'
require 'RRD'

log = File.open("log/snmp.log", "a")
host = ARGV[0]
oid = ARGV[1]
delay = ARGV[2].to_i

#Process.daemon

$0="#{host}_#{oid}"

def snmp_get(host,oid)
  port = '161'
  retrived_data = 0
  SNMP::Manager.open(:Host => host, :Version => :SNMPv2c, :Community => 'public', :port => port) do |manager|
    res = manager.get(oid)
    retrived_data = res.varbind_list.first.value if res.varbind_list.size == 1
  end
  retrived_data
end

def rrd_save(host,oid,data)
  rrd = "rrd_data/#{host}_#{oid}.rrd"
  now = Time.now.to_i
  unless File.exists?(rrd)
    puts "Creating RRD"
    RRD.create(rrd, "--start", "#{now-1}", "--step", "10", "DS:a:GAUGE:600:U:U", "RRA:AVERAGE:0.5:1:300")
  end

  puts "Updating RRD"
  RRD.update(rrd, "#{now}:#{data}")
end

loop do
  data = snmp_get(host,oid)
  rrd_save(host,oid,data)
  sleep(delay)
end

